<!-- HTML header for doxygen 1.8.6-->
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.13"/>
<title>OpenCV: Making your own linear filters!</title>
<link href="../../opencv.ico" rel="shortcut icon" type="image/x-icon" />
<link href="../../tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="../../jquery.js"></script>
<script type="text/javascript" src="../../dynsections.js"></script>
<script type="text/javascript" src="../../tutorial-utils.js"></script>
<link href="../../search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="../../search/searchdata.js"></script>
<script type="text/javascript" src="../../search/search.js"></script>
<script type="text/x-mathjax-config">
  MathJax.Hub.Config({
    extensions: ["tex2jax.js", "TeX/AMSmath.js", "TeX/AMSsymbols.js"],
    jax: ["input/TeX","output/HTML-CSS"],
});
//<![CDATA[
MathJax.Hub.Config(
{
  TeX: {
      Macros: {
          matTT: [ "\\[ \\left|\\begin{array}{ccc} #1 & #2 & #3\\\\ #4 & #5 & #6\\\\ #7 & #8 & #9 \\end{array}\\right| \\]", 9],
          fork: ["\\left\\{ \\begin{array}{l l} #1 & \\mbox{#2}\\\\ #3 & \\mbox{#4}\\\\ \\end{array} \\right.", 4],
          forkthree: ["\\left\\{ \\begin{array}{l l} #1 & \\mbox{#2}\\\\ #3 & \\mbox{#4}\\\\ #5 & \\mbox{#6}\\\\ \\end{array} \\right.", 6],
          forkfour: ["\\left\\{ \\begin{array}{l l} #1 & \\mbox{#2}\\\\ #3 & \\mbox{#4}\\\\ #5 & \\mbox{#6}\\\\ #7 & \\mbox{#8}\\\\ \\end{array} \\right.", 8],
          vecthree: ["\\begin{bmatrix} #1\\\\ #2\\\\ #3 \\end{bmatrix}", 3],
          vecthreethree: ["\\begin{bmatrix} #1 & #2 & #3\\\\ #4 & #5 & #6\\\\ #7 & #8 & #9 \\end{bmatrix}", 9],
          cameramatrix: ["#1 = \\begin{bmatrix} f_x & 0 & c_x\\\\ 0 & f_y & c_y\\\\ 0 & 0 & 1 \\end{bmatrix}", 1],
          distcoeffs: ["(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6 [, s_1, s_2, s_3, s_4[, \\tau_x, \\tau_y]]]]) \\text{ of 4, 5, 8, 12 or 14 elements}"],
          distcoeffsfisheye: ["(k_1, k_2, k_3, k_4)"],
          hdotsfor: ["\\dots", 1],
          mathbbm: ["\\mathbb{#1}", 1],
          bordermatrix: ["\\matrix{#1}", 1]
      }
  }
}
);
//]]>
</script><script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.0/MathJax.js"></script>
<link href="../../doxygen.css" rel="stylesheet" type="text/css" />
<link href="../../stylesheet.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<!--#include virtual="/google-search.html"-->
<table cellspacing="0" cellpadding="0">
 <tbody>
 <tr style="height: 56px;">
  <td id="projectlogo"><img alt="Logo" src="../../opencv-logo-small.png"/></td>
  <td style="padding-left: 0.5em;">
   <div id="projectname">OpenCV
   &#160;<span id="projectnumber">4.5.2</span>
   </div>
   <div id="projectbrief">Open Source Computer Vision</div>
  </td>
 </tr>
 </tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.13 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "../../search",false,'Search');
</script>
<script type="text/javascript" src="../../menudata.js"></script>
<script type="text/javascript" src="../../menu.js"></script>
<script type="text/javascript">
$(function() {
  initMenu('../../',true,false,'search.php','Search');
  $(document).ready(function() { init_search(); });
});
</script>
<div id="main-nav"></div>
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
     onmouseover="return searchBox.OnSearchSelectShow()"
     onmouseout="return searchBox.OnSearchSelectHide()"
     onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>

<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0" 
        name="MSearchResults" id="MSearchResults">
</iframe>
</div>

<div id="nav-path" class="navpath">
  <ul>
<li class="navelem"><a class="el" href="../../d9/df8/tutorial_root.html">OpenCV Tutorials</a></li><li class="navelem"><a class="el" href="../../d7/da8/tutorial_table_of_content_imgproc.html">Image Processing (imgproc module)</a></li>  </ul>
</div>
</div><!-- top -->
<div class="header">
  <div class="headertitle">
<div class="title">Making your own linear filters! </div>  </div>
</div><!--header-->
<div class="contents">
<div class="textblock"><p><b>Prev Tutorial:</b> <a class="el" href="../../da/d97/tutorial_threshold_inRange.html">Thresholding Operations using inRange</a></p>
<p><b>Next Tutorial:</b> <a class="el" href="../../dc/da3/tutorial_copyMakeBorder.html">Adding borders to your images</a></p>
<table class="doxtable">
<tr>
<th align="right"></th><th align="left"></th></tr>
<tr>
<td align="right">Original author </td><td align="left">Ana Huamán </td></tr>
<tr>
<td align="right">Compatibility </td><td align="left">OpenCV &gt;= 3.0 </td></tr>
</table>
<h2>Goal </h2>
<p>In this tutorial you will learn how to:</p>
<ul>
<li>Use the OpenCV function <b><a class="el" href="../../d5/df1/group__imgproc__hal__functions.html#ga42c2468ab3a1238fbf48458c57169081">filter2D()</a></b> to create your own linear filters.</li>
</ul>
<h2>Theory </h2>
<dl class="section note"><dt>Note</dt><dd>The explanation below belongs to the book <b>Learning OpenCV</b> by Bradski and Kaehler.</dd></dl>
<h3>Correlation</h3>
<p>In a very general sense, correlation is an operation between every part of an image and an operator (kernel).</p>
<h3>What is a kernel?</h3>
<p>A kernel is essentially a fixed size array of numerical coefficients along with an <em>anchor point</em> in that array, which is typically located at the center.</p>
<div class="image">
<img src="../../filter_2d_tutorial_kernel_theory.png" alt="filter_2d_tutorial_kernel_theory.png"/>
</div>
<h3>How does correlation with a kernel work?</h3>
<p>Assume you want to know the resulting value of a particular location in the image. The value of the correlation is calculated in the following way:</p>
<ol type="1">
<li>Place the kernel anchor on top of a determined pixel, with the rest of the kernel overlaying the corresponding local pixels in the image.</li>
<li>Multiply the kernel coefficients by the corresponding image pixel values and sum the result.</li>
<li>Place the result to the location of the <em>anchor</em> in the input image.</li>
<li>Repeat the process for all pixels by scanning the kernel over the entire image.</li>
</ol>
<p>Expressing the procedure above in the form of an equation we would have:</p>
<p class="formulaDsp">
\[H(x,y) = \sum_{i=0}^{M_{i} - 1} \sum_{j=0}^{M_{j}-1} I(x+i - a_{i}, y + j - a_{j})K(i,j)\]
</p>
<p>Fortunately, OpenCV provides you with the function <b><a class="el" href="../../d5/df1/group__imgproc__hal__functions.html#ga42c2468ab3a1238fbf48458c57169081">filter2D()</a></b> so you do not have to code all these operations.</p>
<h3>What does this program do?</h3>
<ul>
<li>Loads an image</li>
<li><p class="startli">Performs a <em>normalized box filter</em>. For instance, for a kernel of size \(size = 3\), the kernel would be:</p>
<p class="formulaDsp">
\[K = \dfrac{1}{3 \cdot 3} \begin{bmatrix} 1 &amp; 1 &amp; 1 \\ 1 &amp; 1 &amp; 1 \\ 1 &amp; 1 &amp; 1 \end{bmatrix}\]
</p>
</li>
</ul>
<p>The program will perform the filter operation with kernels of sizes 3, 5, 7, 9 and 11.</p>
<ul>
<li>The filter output (with each kernel) will be shown during 500 milliseconds</li>
</ul>
<h2>Code </h2>
<p>The tutorial code's is shown in the lines below.</p>
 <div class='newInnerHTML' title='cpp' style='display: none;'>C++</div><div class='toggleable_div label_cpp' style='display: none;'><p> You can also download it from <a href="https://raw.githubusercontent.com/opencv/opencv/master/samples/cpp/tutorial_code/ImgTrans/filter2D_demo.cpp">here</a> </p><div class="fragment"><div class="line"></div><div class="line"><span class="preprocessor">#include &quot;<a class="code" href="../../d1/d4f/imgproc_2include_2opencv2_2imgproc_8hpp.html">opencv2/imgproc.hpp</a>&quot;</span></div><div class="line"><span class="preprocessor">#include &quot;<a class="code" href="../../d6/d87/imgcodecs_8hpp.html">opencv2/imgcodecs.hpp</a>&quot;</span></div><div class="line"><span class="preprocessor">#include &quot;<a class="code" href="../../d4/dd5/highgui_8hpp.html">opencv2/highgui.hpp</a>&quot;</span></div><div class="line"></div><div class="line"><span class="keyword">using namespace </span><a class="code" href="../../d2/d75/namespacecv.html">cv</a>;</div><div class="line"></div><div class="line"><span class="keywordtype">int</span> main ( <span class="keywordtype">int</span> argc, <span class="keywordtype">char</span>** argv )</div><div class="line">{</div><div class="line">    <span class="comment">// Declare variables</span></div><div class="line">    <a class="code" href="../../d3/d63/classcv_1_1Mat.html">Mat</a> src, dst;</div><div class="line"></div><div class="line">    <a class="code" href="../../d3/d63/classcv_1_1Mat.html">Mat</a> kernel;</div><div class="line">    <a class="code" href="../../db/d4e/classcv_1_1Point__.html">Point</a> anchor;</div><div class="line">    <span class="keywordtype">double</span> delta;</div><div class="line">    <span class="keywordtype">int</span> ddepth;</div><div class="line">    <span class="keywordtype">int</span> kernel_size;</div><div class="line">    <span class="keyword">const</span> <span class="keywordtype">char</span>* window_name = <span class="stringliteral">&quot;filter2D Demo&quot;</span>;</div><div class="line"></div><div class="line">    <span class="keyword">const</span> <span class="keywordtype">char</span>* imageName = argc &gt;=2 ? argv[1] : <span class="stringliteral">&quot;lena.jpg&quot;</span>;</div><div class="line"></div><div class="line">    <span class="comment">// Loads an image</span></div><div class="line">    src = <a class="code" href="../../d4/da8/group__imgcodecs.html#ga288b8b3da0892bd651fce07b3bbd3a56">imread</a>( <a class="code" href="../../d6/dba/group__core__utils__samples.html#ga3a33b00033b46c698ff6340d95569c13">samples::findFile</a>( imageName ), <a class="code" href="../../d8/d6a/group__imgcodecs__flags.html#gga61d9b0126a3e57d9277ac48327799c80af660544735200cbe942eea09232eb822">IMREAD_COLOR</a> ); <span class="comment">// Load an image</span></div><div class="line"></div><div class="line">    <span class="keywordflow">if</span>( src.<a class="code" href="../../d3/d63/classcv_1_1Mat.html#abbec3525a852e77998aba034813fded4">empty</a>() )</div><div class="line">    {</div><div class="line">        printf(<span class="stringliteral">&quot; Error opening image\n&quot;</span>);</div><div class="line">        printf(<span class="stringliteral">&quot; Program Arguments: [image_name -- default lena.jpg] \n&quot;</span>);</div><div class="line">        <span class="keywordflow">return</span> EXIT_FAILURE;</div><div class="line">    }</div><div class="line"></div><div class="line">    <span class="comment">// Initialize arguments for the filter</span></div><div class="line">    anchor = <a class="code" href="../../dc/d84/group__core__basic.html#ga1e83eafb2d26b3c93f09e8338bcab192">Point</a>( -1, -1 );</div><div class="line">    delta = 0;</div><div class="line">    ddepth = -1;</div><div class="line"></div><div class="line">    <span class="comment">// Loop - Will filter the image with different kernel sizes each 0.5 seconds</span></div><div class="line">    <span class="keywordtype">int</span> ind = 0;</div><div class="line">    <span class="keywordflow">for</span>(;;)</div><div class="line">    {</div><div class="line">        <span class="comment">// Update kernel size for a normalized box filter</span></div><div class="line">        kernel_size = 3 + 2*( ind%5 );</div><div class="line">        kernel = <a class="code" href="../../d3/d63/classcv_1_1Mat.html#a69ae0402d116fc9c71908d8508dc2f09">Mat::ones</a>( kernel_size, kernel_size, <a class="code" href="../../d1/d1b/group__core__hal__interface.html#ga4a3def5d72b74bed31f5f8ab7676099c">CV_32F</a> )/ (float)(kernel_size*kernel_size);</div><div class="line"></div><div class="line">        <span class="comment">// Apply filter</span></div><div class="line">        <a class="code" href="../../d4/d86/group__imgproc__filter.html#ga27c049795ce870216ddfb366086b5a04">filter2D</a>(src, dst, ddepth , kernel, anchor, delta, <a class="code" href="../../d2/de8/group__core__array.html#gga209f2f4869e304c82d07739337eae7c5afe14c13a4ea8b8e3b3ef399013dbae01">BORDER_DEFAULT</a> );</div><div class="line">        <a class="code" href="../../d7/dfc/group__highgui.html#ga453d42fe4cb60e5723281a89973ee563">imshow</a>( window_name, dst );</div><div class="line"></div><div class="line">        <span class="keywordtype">char</span> c = (char)<a class="code" href="../../d7/dfc/group__highgui.html#ga5628525ad33f52eab17feebcfba38bd7">waitKey</a>(500);</div><div class="line">        <span class="comment">// Press &#39;ESC&#39; to exit the program</span></div><div class="line">        <span class="keywordflow">if</span>( c == 27 )</div><div class="line">        { <span class="keywordflow">break</span>; }</div><div class="line"></div><div class="line">        ind++;</div><div class="line">    }</div><div class="line"></div><div class="line">    <span class="keywordflow">return</span> EXIT_SUCCESS;</div><div class="line">}</div></div><!-- fragment -->  </div>  <div class='newInnerHTML' title='java' style='display: none;'>Java</div><div class='toggleable_div label_java' style='display: none;'><p> You can also download it from <a href="https://raw.githubusercontent.com/opencv/opencv/master/samples/java/tutorial_code/ImgTrans/Filter2D/Filter2D_Demo.java">here</a> </p><div class="fragment"><div class="line"></div><div class="line"><span class="keyword">import</span> org.opencv.core.*;</div><div class="line"><span class="keyword">import</span> org.opencv.core.Point;</div><div class="line"><span class="keyword">import</span> org.opencv.highgui.HighGui;</div><div class="line"><span class="keyword">import</span> org.opencv.imgcodecs.Imgcodecs;</div><div class="line"><span class="keyword">import</span> org.opencv.imgproc.Imgproc;</div><div class="line"></div><div class="line"><span class="keyword">class </span>Filter2D_DemoRun {</div><div class="line"></div><div class="line">    <span class="keyword">public</span> <span class="keywordtype">void</span> run(<a class="code" href="../../dc/d84/group__core__basic.html#ga1f6634802eeadfd7245bc75cf3e216c2">String</a>[] args) {</div><div class="line">        <span class="comment">// Declare variables</span></div><div class="line">        Mat src, dst = <span class="keyword">new</span> Mat();</div><div class="line"></div><div class="line">        Mat kernel = <span class="keyword">new</span> Mat();</div><div class="line">        <a class="code" href="../../dc/d84/group__core__basic.html#ga1e83eafb2d26b3c93f09e8338bcab192">Point</a> anchor;</div><div class="line">        <span class="keywordtype">double</span> delta;</div><div class="line">        <span class="keywordtype">int</span> ddepth;</div><div class="line">        <span class="keywordtype">int</span> kernel_size;</div><div class="line">        <a class="code" href="../../dc/d84/group__core__basic.html#ga1f6634802eeadfd7245bc75cf3e216c2">String</a> window_name = <span class="stringliteral">&quot;filter2D Demo&quot;</span>;</div><div class="line"></div><div class="line">        <a class="code" href="../../dc/d84/group__core__basic.html#ga1f6634802eeadfd7245bc75cf3e216c2">String</a> imageName = ((args.length &gt; 0) ? args[0] : <span class="stringliteral">&quot;../data/lena.jpg&quot;</span>);</div><div class="line"></div><div class="line">        <span class="comment">// Load an image</span></div><div class="line">        src = Imgcodecs.imread(imageName, Imgcodecs.IMREAD_COLOR);</div><div class="line"></div><div class="line">        <span class="comment">// Check if image is loaded fine</span></div><div class="line">        <span class="keywordflow">if</span>( src.empty() ) {</div><div class="line">            System.out.println(<span class="stringliteral">&quot;Error opening image!&quot;</span>);</div><div class="line">            System.out.println(<span class="stringliteral">&quot;Program Arguments: [image_name -- default ../data/lena.jpg] \n&quot;</span>);</div><div class="line">            System.exit(-1);</div><div class="line">        }</div><div class="line"></div><div class="line">        <span class="comment">// Initialize arguments for the filter</span></div><div class="line">        anchor = <span class="keyword">new</span> <a class="code" href="../../dc/d84/group__core__basic.html#ga1e83eafb2d26b3c93f09e8338bcab192">Point</a>( -1, -1);</div><div class="line">        delta = 0.0;</div><div class="line">        ddepth = -1;</div><div class="line"></div><div class="line">        <span class="comment">// Loop - Will filter the image with different kernel sizes each 0.5 seconds</span></div><div class="line">        <span class="keywordtype">int</span> ind = 0;</div><div class="line">        <span class="keywordflow">while</span>( <span class="keyword">true</span> )</div><div class="line">        {</div><div class="line">            <span class="comment">// Update kernel size for a normalized box filter</span></div><div class="line">            kernel_size = 3 + 2*( ind%5 );</div><div class="line">            Mat ones = Mat.ones( kernel_size, kernel_size, CvType.CV_32F );</div><div class="line">            Core.multiply(ones, <span class="keyword">new</span> <a class="code" href="../../dc/d84/group__core__basic.html#ga599fe92e910c027be274233eccad7beb">Scalar</a>(1/(<span class="keywordtype">double</span>)(kernel_size*kernel_size)), kernel);</div><div class="line"></div><div class="line">            <span class="comment">// Apply filter</span></div><div class="line">            Imgproc.filter2D(src, dst, ddepth , kernel, anchor, delta, Core.BORDER_DEFAULT );</div><div class="line">            HighGui.imshow( window_name, dst );</div><div class="line"></div><div class="line">            <span class="keywordtype">int</span> c = HighGui.waitKey(500);</div><div class="line">            <span class="comment">// Press &#39;ESC&#39; to exit the program</span></div><div class="line">            <span class="keywordflow">if</span>( c == 27 )</div><div class="line">            { <span class="keywordflow">break</span>; }</div><div class="line"></div><div class="line">            ind++;</div><div class="line">        }</div><div class="line"></div><div class="line">        System.exit(0);</div><div class="line">    }</div><div class="line">}</div><div class="line"></div><div class="line"><span class="keyword">public</span> <span class="keyword">class </span>Filter2D_Demo {</div><div class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keywordtype">void</span> main(<a class="code" href="../../dc/d84/group__core__basic.html#ga1f6634802eeadfd7245bc75cf3e216c2">String</a>[] args) {</div><div class="line">        <span class="comment">// Load the native library.</span></div><div class="line">        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);</div><div class="line">        <span class="keyword">new</span> Filter2D_DemoRun().run(args);</div><div class="line">    }</div><div class="line">}</div></div><!-- fragment -->  </div>  <div class='newInnerHTML' title='python' style='display: none;'>Python</div><div class='toggleable_div label_python' style='display: none;'><p> You can also download it from <a href="https://raw.githubusercontent.com/opencv/opencv/master/samples/python/tutorial_code/ImgTrans/Filter2D/filter2D.py">here</a> </p><div class="fragment"><div class="line"><span class="stringliteral">&quot;&quot;&quot;</span></div><div class="line"><span class="stringliteral">@file filter2D.py</span></div><div class="line"><span class="stringliteral">@brief Sample code that shows how to implement your own linear filters by using filter2D function</span></div><div class="line"><span class="stringliteral">&quot;&quot;&quot;</span></div><div class="line"><span class="keyword">import</span> sys</div><div class="line"><span class="keyword">import</span> cv2 <span class="keyword">as</span> cv</div><div class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</div><div class="line"></div><div class="line"></div><div class="line"><span class="keyword">def </span>main(argv):</div><div class="line">    window_name = <span class="stringliteral">&#39;filter2D Demo&#39;</span></div><div class="line"></div><div class="line">    </div><div class="line">    imageName = argv[0] <span class="keywordflow">if</span> len(argv) &gt; 0 <span class="keywordflow">else</span> <span class="stringliteral">&#39;lena.jpg&#39;</span></div><div class="line"></div><div class="line">    <span class="comment"># Loads an image</span></div><div class="line">    src = <a class="code" href="../../d4/da8/group__imgcodecs.html#ga288b8b3da0892bd651fce07b3bbd3a56">cv.imread</a>(<a class="code" href="../../d6/dba/group__core__utils__samples.html#ga3a33b00033b46c698ff6340d95569c13">cv.samples.findFile</a>(imageName), cv.IMREAD_COLOR)</div><div class="line"></div><div class="line">    <span class="comment"># Check if image is loaded fine</span></div><div class="line">    <span class="keywordflow">if</span> src <span class="keywordflow">is</span> <span class="keywordtype">None</span>:</div><div class="line">        <span class="keywordflow">print</span> (<span class="stringliteral">&#39;Error opening image!&#39;</span>)</div><div class="line">        <span class="keywordflow">print</span> (<span class="stringliteral">&#39;Usage: filter2D.py [image_name -- default lena.jpg] \n&#39;</span>)</div><div class="line">        <span class="keywordflow">return</span> -1</div><div class="line">    </div><div class="line">    ddepth = -1</div><div class="line">    </div><div class="line">    ind = 0</div><div class="line">    <span class="keywordflow">while</span> <span class="keyword">True</span>:</div><div class="line">        </div><div class="line">        kernel_size = 3 + 2 * (ind % 5)</div><div class="line">        kernel = np.ones((kernel_size, kernel_size), dtype=np.float32)</div><div class="line">        kernel /= (kernel_size * kernel_size)</div><div class="line">        </div><div class="line">        dst = <a class="code" href="../../d4/d86/group__imgproc__filter.html#ga27c049795ce870216ddfb366086b5a04">cv.filter2D</a>(src, ddepth, kernel)</div><div class="line">        </div><div class="line">        <a class="code" href="../../df/d24/group__highgui__opengl.html#gaae7e90aa3415c68dba22a5ff2cefc25d">cv.imshow</a>(window_name, dst)</div><div class="line"></div><div class="line">        c = <a class="code" href="../../d7/dfc/group__highgui.html#ga5628525ad33f52eab17feebcfba38bd7">cv.waitKey</a>(500)</div><div class="line">        <span class="keywordflow">if</span> c == 27:</div><div class="line">            <span class="keywordflow">break</span></div><div class="line"></div><div class="line">        ind += 1</div><div class="line"></div><div class="line">    <span class="keywordflow">return</span> 0</div><div class="line"></div><div class="line"></div><div class="line"><span class="keywordflow">if</span> __name__ == <span class="stringliteral">&quot;__main__&quot;</span>:</div><div class="line">    main(sys.argv[1:])</div></div><!-- fragment -->  </div> <h2>Explanation </h2>
<h4>Load an image</h4>
 <div class='newInnerHTML' title='cpp' style='display: none;'>C++</div><div class='toggleable_div label_cpp' style='display: none;'> <div class="fragment"><div class="line">    <span class="keyword">const</span> <span class="keywordtype">char</span>* imageName = argc &gt;=2 ? argv[1] : <span class="stringliteral">&quot;lena.jpg&quot;</span>;</div><div class="line"></div><div class="line">    <span class="comment">// Loads an image</span></div><div class="line">    src = <a class="code" href="../../d4/da8/group__imgcodecs.html#ga288b8b3da0892bd651fce07b3bbd3a56">imread</a>( <a class="code" href="../../d6/dba/group__core__utils__samples.html#ga3a33b00033b46c698ff6340d95569c13">samples::findFile</a>( imageName ), <a class="code" href="../../d8/d6a/group__imgcodecs__flags.html#gga61d9b0126a3e57d9277ac48327799c80af660544735200cbe942eea09232eb822">IMREAD_COLOR</a> ); <span class="comment">// Load an image</span></div><div class="line"></div><div class="line">    <span class="keywordflow">if</span>( src.empty() )</div><div class="line">    {</div><div class="line">        printf(<span class="stringliteral">&quot; Error opening image\n&quot;</span>);</div><div class="line">        printf(<span class="stringliteral">&quot; Program Arguments: [image_name -- default lena.jpg] \n&quot;</span>);</div><div class="line">        <span class="keywordflow">return</span> EXIT_FAILURE;</div><div class="line">    }</div></div><!-- fragment --> </div>  <div class='newInnerHTML' title='java' style='display: none;'>Java</div><div class='toggleable_div label_java' style='display: none;'> <div class="fragment"><div class="line">        <a class="code" href="../../dc/d84/group__core__basic.html#ga1f6634802eeadfd7245bc75cf3e216c2">String</a> imageName = ((args.length &gt; 0) ? args[0] : <span class="stringliteral">&quot;../data/lena.jpg&quot;</span>);</div><div class="line"></div><div class="line">        <span class="comment">// Load an image</span></div><div class="line">        src = Imgcodecs.imread(imageName, Imgcodecs.IMREAD_COLOR);</div><div class="line"></div><div class="line">        <span class="comment">// Check if image is loaded fine</span></div><div class="line">        <span class="keywordflow">if</span>( src.empty() ) {</div><div class="line">            System.out.println(<span class="stringliteral">&quot;Error opening image!&quot;</span>);</div><div class="line">            System.out.println(<span class="stringliteral">&quot;Program Arguments: [image_name -- default ../data/lena.jpg] \n&quot;</span>);</div><div class="line">            System.exit(-1);</div><div class="line">        }</div></div><!-- fragment --> </div>  <div class='newInnerHTML' title='python' style='display: none;'>Python</div><div class='toggleable_div label_python' style='display: none;'> <div class="fragment"><div class="line">    imageName = argv[0] <span class="keywordflow">if</span> len(argv) &gt; 0 <span class="keywordflow">else</span> <span class="stringliteral">&#39;lena.jpg&#39;</span></div><div class="line"></div><div class="line">    <span class="comment"># Loads an image</span></div><div class="line">    src = <a class="code" href="../../d4/da8/group__imgcodecs.html#ga288b8b3da0892bd651fce07b3bbd3a56">cv.imread</a>(<a class="code" href="../../d6/dba/group__core__utils__samples.html#ga3a33b00033b46c698ff6340d95569c13">cv.samples.findFile</a>(imageName), cv.IMREAD_COLOR)</div><div class="line"></div><div class="line">    <span class="comment"># Check if image is loaded fine</span></div><div class="line">    <span class="keywordflow">if</span> src <span class="keywordflow">is</span> <span class="keywordtype">None</span>:</div><div class="line">        <span class="keywordflow">print</span> (<span class="stringliteral">&#39;Error opening image!&#39;</span>)</div><div class="line">        <span class="keywordflow">print</span> (<span class="stringliteral">&#39;Usage: filter2D.py [image_name -- default lena.jpg] \n&#39;</span>)</div><div class="line">        <span class="keywordflow">return</span> -1</div></div><!-- fragment --> </div> <h4>Initialize the arguments</h4>
 <div class='newInnerHTML' title='cpp' style='display: none;'>C++</div><div class='toggleable_div label_cpp' style='display: none;'> <div class="fragment"><div class="line">    <span class="comment">// Initialize arguments for the filter</span></div><div class="line">    anchor = <a class="code" href="../../dc/d84/group__core__basic.html#ga1e83eafb2d26b3c93f09e8338bcab192">Point</a>( -1, -1 );</div><div class="line">    delta = 0;</div><div class="line">    ddepth = -1;</div></div><!-- fragment --> </div>  <div class='newInnerHTML' title='java' style='display: none;'>Java</div><div class='toggleable_div label_java' style='display: none;'> <div class="fragment"><div class="line">        <span class="comment">// Initialize arguments for the filter</span></div><div class="line">        anchor = <span class="keyword">new</span> <a class="code" href="../../dc/d84/group__core__basic.html#ga1e83eafb2d26b3c93f09e8338bcab192">Point</a>( -1, -1);</div><div class="line">        delta = 0.0;</div><div class="line">        ddepth = -1;</div></div><!-- fragment --> </div>  <div class='newInnerHTML' title='python' style='display: none;'>Python</div><div class='toggleable_div label_python' style='display: none;'> <div class="fragment"><div class="line">    <span class="comment"># Initialize ddepth argument for the filter</span></div><div class="line">    ddepth = -1</div></div><!-- fragment --> </div> <h5>Loop</h5>
<p>Perform an infinite loop updating the kernel size and applying our linear filter to the input image. Let's analyze that more in detail:</p>
<ul>
<li>First we define the kernel our filter is going to use. Here it is:</li>
</ul>
 <div class='newInnerHTML' title='cpp' style='display: none;'>C++</div><div class='toggleable_div label_cpp' style='display: none;'> <div class="fragment"><div class="line">        <span class="comment">// Update kernel size for a normalized box filter</span></div><div class="line">        kernel_size = 3 + 2*( ind%5 );</div><div class="line">        kernel = Mat::ones( kernel_size, kernel_size, <a class="code" href="../../d1/d1b/group__core__hal__interface.html#ga4a3def5d72b74bed31f5f8ab7676099c">CV_32F</a> )/ (float)(kernel_size*kernel_size);</div></div><!-- fragment --> </div>  <div class='newInnerHTML' title='java' style='display: none;'>Java</div><div class='toggleable_div label_java' style='display: none;'> <div class="fragment"><div class="line">            <span class="comment">// Update kernel size for a normalized box filter</span></div><div class="line">            kernel_size = 3 + 2*( ind%5 );</div><div class="line">            Mat ones = Mat.ones( kernel_size, kernel_size, CvType.CV_32F );</div><div class="line">            Core.multiply(ones, <span class="keyword">new</span> <a class="code" href="../../dc/d84/group__core__basic.html#ga599fe92e910c027be274233eccad7beb">Scalar</a>(1/(<span class="keywordtype">double</span>)(kernel_size*kernel_size)), kernel);</div></div><!-- fragment --> </div>  <div class='newInnerHTML' title='python' style='display: none;'>Python</div><div class='toggleable_div label_python' style='display: none;'> <div class="fragment"><div class="line">        <span class="comment"># Update kernel size for a normalized box filter</span></div><div class="line">        kernel_size = 3 + 2 * (ind % 5)</div><div class="line">        kernel = np.ones((kernel_size, kernel_size), dtype=np.float32)</div><div class="line">        kernel /= (kernel_size * kernel_size)</div></div><!-- fragment --> </div> <p>The first line is to update the <em>kernel_size</em> to odd values in the range: \([3,11]\). The second line actually builds the kernel by setting its value to a matrix filled with \(1&#39;s\) and normalizing it by dividing it between the number of elements.</p>
<ul>
<li>After setting the kernel, we can generate the filter by using the function <b><a class="el" href="../../d5/df1/group__imgproc__hal__functions.html#ga42c2468ab3a1238fbf48458c57169081">filter2D()</a></b> :</li>
</ul>
 <div class='newInnerHTML' title='cpp' style='display: none;'>C++</div><div class='toggleable_div label_cpp' style='display: none;'> <div class="fragment"><div class="line">        <span class="comment">// Apply filter</span></div><div class="line">        <a class="code" href="../../d5/df1/group__imgproc__hal__functions.html#ga42c2468ab3a1238fbf48458c57169081">filter2D</a>(src, dst, ddepth , kernel, anchor, delta, <a class="code" href="../../d2/de8/group__core__array.html#gga209f2f4869e304c82d07739337eae7c5afe14c13a4ea8b8e3b3ef399013dbae01">BORDER_DEFAULT</a> );</div></div><!-- fragment --> </div>  <div class='newInnerHTML' title='java' style='display: none;'>Java</div><div class='toggleable_div label_java' style='display: none;'> <div class="fragment"><div class="line">            <span class="comment">// Apply filter</span></div><div class="line">            Imgproc.filter2D(src, dst, ddepth , kernel, anchor, delta, Core.BORDER_DEFAULT );</div></div><!-- fragment --> </div>  <div class='newInnerHTML' title='python' style='display: none;'>Python</div><div class='toggleable_div label_python' style='display: none;'> <div class="fragment"><div class="line">        <span class="comment"># Apply filter</span></div><div class="line">        dst = <a class="code" href="../../d4/d86/group__imgproc__filter.html#ga27c049795ce870216ddfb366086b5a04">cv.filter2D</a>(src, ddepth, kernel)</div></div><!-- fragment --> </div> <ul>
<li>The arguments denote:<ul>
<li><em>src</em>: Source image</li>
<li><em>dst</em>: Destination image</li>
<li><em>ddepth</em>: The depth of <em>dst</em>. A negative value (such as \(-1\)) indicates that the depth is the same as the source.</li>
<li><em>kernel</em>: The kernel to be scanned through the image</li>
<li><em>anchor</em>: The position of the anchor relative to its kernel. The location <em>Point(-1, -1)</em> indicates the center by default.</li>
<li><em>delta</em>: A value to be added to each pixel during the correlation. By default it is \(0\)</li>
<li><em>BORDER_DEFAULT</em>: We let this value by default (more details in the following tutorial)</li>
</ul>
</li>
<li>Our program will effectuate a <em>while</em> loop, each 500 ms the kernel size of our filter will be updated in the range indicated.</li>
</ul>
<h2>Results </h2>
<ol type="1">
<li>After compiling the code above, you can execute it giving as argument the path of an image. The result should be a window that shows an image blurred by a normalized filter. Each 0.5 seconds the kernel size should change, as can be seen in the series of snapshots below:</li>
</ol>
<div class="image">
<img src="../../filter_2d_tutorial_result.jpg" alt="filter_2d_tutorial_result.jpg"/>
</div>
 </div></div><!-- contents -->
<!-- HTML footer for doxygen 1.8.6-->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated on Fri Apr 2 2021 11:36:35 for OpenCV by &#160;<a href="http://www.doxygen.org/index.html">
<img class="footer" src="../../doxygen.png" alt="doxygen"/>
</a> 1.8.13
</small></address>
<script type="text/javascript">
//<![CDATA[
addTutorialsButtons();
//]]>
</script>
</body>
</html>
